from flask import Blueprint, request, jsonify
from applications.extensions import db
from applications.models.backend import Permission

permission_bp = Blueprint('permission', __name__, url_prefix='/system/permission')

# 获取所有权限
@permission_bp.route('/list', methods=['GET'])
def get_permissions():
    permissions = Permission.query.all()
    permission_list = [{
        'id': p.id,
        'name': p.name,
        'code': p.code,
        'description': p.description,
        'endpoint': p.endpoint
    } for p in permissions]
    return jsonify({'code': 200, 'data': permission_list})

# 新增权限
@permission_bp.route('/add', methods=['POST'])
def add_permission():
    data = request.get_json()
    if not data or 'name' not in data or 'code' not in data:
        return jsonify({'code': 400, 'message': '权限名称和代码是必填项'}), 400

    if Permission.query.filter_by(code=data['code']).first():
        return jsonify({'code': 409, 'message': '权限代码已存在'}), 409

    new_permission = Permission(
        name=data['name'],
        code=data['code'],
        description=data.get('description'),
        endpoint=data.get('endpoint')
    )
    db.session.add(new_permission)
    db.session.commit()
    return jsonify({'code': 201, 'message': '权限创建成功'}), 201

# 修改权限
@permission_bp.route('/update', methods=['POST'])
def update_permission():
    data = request.get_json()
    permission_id = data.get('id')
    if not permission_id:
        return jsonify({'code': 400, 'message': 'Permission ID is required'}), 400

    permission = Permission.query.get(permission_id)
    if not permission:
        return jsonify({'code': 404, 'message': 'Permission not found'}), 404

    permission.name = data.get('name', permission.name)
    permission.code = data.get('code', permission.code)
    permission.description = data.get('description', permission.description)
    permission.endpoint = data.get('endpoint', permission.endpoint)

    db.session.commit()
    return jsonify({'code': 200, 'message': '权限更新成功'})

# 删除权限
@permission_bp.route('/delete', methods=['POST'])
def delete_permission():
    permission_id = request.json.get('id')
    if not permission_id:
        return jsonify({'code': 400, 'message': 'Permission ID is required'}), 400
        
    permission = Permission.query.get(permission_id)
    if not permission:
        return jsonify({'code': 404, 'message': 'Permission not found'}), 404

    db.session.delete(permission)
    db.session.commit()
    return jsonify({'code': 200, 'message': 'Permission deleted successfully'})

def register_permission_bps(app):
    app.register_blueprint(permission_bp)